var tousername;
var username;
var password;
var apiURL = null;
var curUserId = null;
var curChatUserId = null;
var conn = null;
var curRoomId = null;
var msgCardDivId = "chat01";
var talkToDivId = "talkTo";
var talkInputId = "talkInputId";
var fileInputId = "fileInput";
var bothRoster = [];
var toRoster = [];
var maxWidth = 200;
var groupFlagMark = "group--";
var groupQuering = false;
var textSending = false;
var appkey = "feellike21#kaiwuhealth";
var time = 0;

window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
var getLoginInfo = function() {
	return {
		isLogin : false
	};
};
var showLoginUI = function() {
	// $('#loginmodal').modal('show');
	// $('#username').focus();
	login();
};
var hiddenLoginUI = function() {
	$('#loginmodal').modal('hide');
};
var showWaitLoginedUI = function() {
	$('#waitLoginmodal').modal('show');
};
var hiddenWaitLoginedUI = function() {
	$('#waitLoginmodal').modal('hide');
};
var showChatUI = function() {
	$('#content').css({
		"display" : "block"
	});
	// var login_userEle = document.getElementById("login_user").children[0];
	// login_userEle.innerHTML = curUserId;
	// login_userEle.setAttribute("title", curUserId);
};
// 登录之前不显示web对话框
var hiddenChatUI = function() {
	$('#content').css({
		"display" : "none"
	});
	document.getElementById(talkInputId).value = "";
};
// 定义消息编辑文本域的快捷键，enter和ctrl+enter为发送，alt+enter为换行
// 控制提交频率
$(function() {
	$("textarea").keydown(function(event) {
		if (event.altKey && event.keyCode == 13) {
			e = $(this).val();
			$(this).val(e + '\n');
		} else if (event.ctrlKey && event.keyCode == 13) {
			// e = $(this).val();
			// $(this).val(e + '<br>');
			event.returnValue = false;
			sendText();
			return false;
		} else if (event.keyCode == 13) {
			event.returnValue = false;
			sendText();
			return false;
		}

	});
});
// easemobwebim-sdk注册回调函数列表
$(document).ready(function() {
	conn = new Easemob.im.Connection();
	// 初始化连接
	conn.init({
		https : false,
		// 当连接成功时的回调方法
		onOpened : function() {
			handleOpen(conn);
		},
		// 当连接关闭时的回调方法
		onClosed : function() {
			handleClosed();
		},
		// 收到文本消息时的回调方法
		onTextMessage : function(message) {
			handleTextMessage(message);
		},
		// 收到表情消息时的回调方法
		onEmotionMessage : function(message) {
			handleEmotion(message);
		},
		// 收到图片消息时的回调方法
		onPictureMessage : function(message) {
			handlePictureMessage(message);
		},
		// 收到音频消息的回调方法
		onAudioMessage : function(message) {
			handleAudioMessage(message);
		},
		// 收到位置消息的回调方法
		onLocationMessage : function(message) {
			handleLocationMessage(message);
		},
		// 收到文件消息的回调方法
		onFileMessage : function(message) {
			handleFileMessage(message);
		},
		// 收到视频消息的回调方法
		onVideoMessage : function(message) {
			handleVideoMessage(message);
		},
		// 收到联系人订阅请求的回调方法
		onPresence : function(message) {
			handlePresence(message);
		},
		// 收到联系人信息的回调方法
		onRoster : function(message) {
			handleRoster(message);
		},
		// 收到群组邀请时的回调方法
		onInviteMessage : function(message) {
			handleInviteMessage(message);
		},
		// 异常时的回调方法
		onError : function(message) {
			handleError(message);
		}
	});
	// 显示登录或者等待页面
	var loginInfo = getLoginInfo();
	if (loginInfo.isLogin) {
		showWaitLoginedUI();
	} else {
		showLoginUI();
	}
	// 发送文件的模态窗口
	$('#fileModal').on('hidden.bs.modal', function(e) {
		var ele = document.getElementById(fileInputId);
		ele.value = "";
		if (!window.addEventListener) {
			ele.outerHTML = ele.outerHTML;
		}
		document.getElementById("fileSend").disabled = false;
		document.getElementById("cancelfileSend").disabled = false;
	});
	// 一般消息
	$('#notice-block-div').on('hidden.bs.modal', function(e) {

	});
	// 在 密码输入框时的回车登录
	$('#password').keypress(function(e) {
		var key = e.which;
		if (key == 13) {
			login();
		}
	});
	$(function() {
		$(window).bind('beforeunload', function() {
			if (conn) {
				conn.close();
				if (navigator.userAgent.indexOf("Firefox") > 0)
					return ' ';
				else
					return '';
			}
		});
	});
});
// 处理连接时函数,主要是登录成功后对页面元素做处理
var handleOpen = function(conn) {
	// 从连接中获取到当前的登录人注册帐号名
	curUserId = conn.context.userId;
	// 获取当前登录人的联系人列表
	// hiddenWaitLoginedUI();
	// showChatUI();
	conn.getRoster({
		success : function(roster) {
			// 页面处理
			hiddenWaitLoginedUI();
			showChatUI();
			var curroster;
			for ( var i in roster) {
				var ros = roster[i];
				// both为双方互为好友，要显示的联系人,from我是对方的单向好友
				if (ros.subscription == 'both' || ros.subscription == 'from') {
					bothRoster.push(ros);
				} else if (ros.subscription == 'to') {
					// to表明了联系人是我的单向好友
					toRoster.push(ros);
				}
			}
			if (bothRoster.length > 0) {
				curroster = bothRoster[0];
				buildContactDiv("contractlist", bothRoster);// 联系人列表页面处理
				if (curroster)
					setCurrentContact(tousername);// 页面处理将第一个联系人作为当前聊天div
			}
			// 获取当前登录人的群组列表
		}
	});

	conn.setPresence();

};
// 连接中断时的处理，主要是对页面进行处理
var handleClosed = function() {
	curUserId = null;
	curChatUserId = null;
	curRoomId = null;
	bothRoster = [];
	toRoster = [];
	hiddenChatUI();
	clearContactUI("contactlistUL", "contactgrouplistUL", "momogrouplistUL",
			msgCardDivId);

	showLoginUI();
	groupQuering = false;
	textSending = false;
};
// 异常情况下的处理方法
var handleError = function(e) {
	if (curUserId == null) {
		hiddenWaitLoginedUI();
		alert(e.msg + ",请重新登录");
		showLoginUI();
	} else {
		var msg = e.msg;
		if (e.type == EASEMOB_IM_CONNCTION_SERVER_CLOSE_ERROR) {
			if (msg == "" || msg == 'unknown') {
				alert("服务器器断开连接,可能是因为在别处登录");
			} else {
				alert("服务器器断开连接");
			}
		} else {
			alert(msg);
		}
	}
};
var logout = function() {
	conn.close();
};
// 设置当前显示的聊天窗口div，如果有联系人则默认选中联系人中的第一个联系人，如没有联系人则当前div为null-nouser
var setCurrentContact = function(defaultUserId) {
	showContactChatDiv(defaultUserId);
	if (curChatUserId != null) {
		hiddenContactChatDiv(curChatUserId);
	} else {
		$('#null-nouser').css({
			"display" : "none"
		});
	}
	curChatUserId = defaultUserId;
};
// 构造当前聊天记录的窗口div
var getContactChatDiv = function(chatUserId) {
	return document.getElementById(curUserId + "-" + chatUserId);
};

// 如果当前没有某一个联系人的聊天窗口div就新建一个
var createContactChatDiv = function(chatUserId) {
	if (chatUserId) {
		var msgContentDivId = curUserId + "-" + chatUserId;
		var newContent = document.createElement("div");
		//alert("创建聊天窗口");
		$(newContent).attr({
			"id" : msgContentDivId,
			"class" : "chat01_content",
			"className" : "chat01_content",
			"style" : "display:none"
		});
		return newContent;
	}
};
var clearContactUI = function(contactlistUL, contactgrouplistUL,
		momogrouplistUL, contactChatDiv) {
	/*
	 * //清除左侧联系人内容 $('#contactlistUL').empty();
	 * $('#contactgrouplistUL').empty(); $('#momogrouplistUL').empty();
	 * 
	 * //处理联系人分组的未读消息处理 var accordionChild = $('#accordionDiv').children(); for
	 * (var i = 1; i <= accordionChild.length; i++) { var badgegroup =
	 * $('#accordion' + i).find(".badgegroup"); if (badgegroup &&
	 * badgegroup.length > 0) { $('#accordion' + i).children().remove(); } } ;
	 */

	// 清除右侧对话框内容
	document.getElementById(talkToDivId).children[0].innerHTML = "";
	var chatRootDiv = document.getElementById(contactChatDiv);
	var children = chatRootDiv.children;
	for (var i = children.length - 1; i > 1; i--) {
		chatRootDiv.removeChild(children[i]);
	}
	$('#null-nouser').css({
		"display" : "block"
	});
};
var emotionFlag = false;
var showEmotionDialog = function() {
	if (emotionFlag) {
		$('#wl_faces_box').css({
			"display" : "block"
		});
		return;
	}
	emotionFlag = true;
	// Easemob.im.Helper.EmotionPicData设置表情的json数组
	var sjson = Easemob.im.Helper.EmotionPicData;
	for ( var key in sjson) {
		var emotions = $('<img>').attr({
			"id" : key,
			"src" : sjson[key],
			"style" : "cursor:pointer;"
		}).click(function() {
			selectEmotionImg(this);
		});
		$('<li>').append(emotions).appendTo($('#emotionUL'));
	}
	$('#wl_faces_box').css({
		"display" : "block"
	});
};
// 表情选择div的关闭方法
var turnoffFaces_box = function() {
	$("#wl_faces_box").fadeOut("slow");
};
var selectEmotionImg = function(selImg) {
	var txt = document.getElementById(talkInputId);
	txt.value = txt.value + selImg.id;
	txt.focus();
};
var showSendPic = function() {
	$('#fileModal').modal('toggle');
	$('#sendfiletype').val('pic');
	$('#send-file-warning').html("");
};
var showSendAudio = function() {
	$('#fileModal').modal('toggle');
	$('#sendfiletype').val('audio');
	$('#send-file-warning').html("");
};
var sendText = function() {

	if (textSending) {
		return;
	}
	textSending = true;

	var msgInput = document.getElementById(talkInputId);
	var msg = msgInput.value;

	if (msg == null || msg.length == 0) {
		return;
	}
	var to = tousername;

	if (to == null) {
		return;
	}
	var options = {
		to : to,
		msg : msg,
		type : "chat"
	};
	// 群组消息和个人消息的判断分支
	// if (to.indexOf(groupFlagMark) >= 0) {
	// options.type = 'groupchat';
	// options.to = curRoomId;
	// }
	// easemobwebim-sdk发送文本消息的方法 to为发送给谁，meg为文本消息对象
	conn.sendTextMessage(options);

	// 当前登录人发送的信息在聊天窗口中原样显示
	var msgtext = msg.replace(/\n/g, '<br>');
	// alert(curUserId);
	// alert(to);
	// alert(msgtext);
	appendMsg(curUserId, to, msgtext);
	turnoffFaces_box();
	msgInput.value = "";
	msgInput.focus();

	setTimeout(function() {
		textSending = false;
	}, 1000);

	insertChatRecord(msgtext, "text");
};

var pictype = {
	"jpg" : true,
	"gif" : true,
	"png" : true,
	"bmp" : true
};
var sendFile = function() {
	var type = $("#sendfiletype").val();
	if (type == 'pic') {
		sendPic();
	} else {
		sendAudio();
	}
};
// 发送图片消息时调用方法
var sendPic = function() {
	var to = curChatUserId;
	if (to == null) {
		return;
	}
	// Easemob.im.Helper.getFileUrl为easemobwebim-sdk获取发送文件对象的方法，fileInputId为
	// input 标签的id值
	var fileObj = Easemob.im.Helper.getFileUrl(fileInputId);
	if (fileObj.url == null || fileObj.url == '') {
		$('#send-file-warning').html("<font color='#FF0000'>请选择发送图片</font>");
		return;
	}
	var filetype = fileObj.filetype;
	var filename = fileObj.filename;
	if (filetype in pictype) {
		document.getElementById("fileSend").disabled = true;
		document.getElementById("cancelfileSend").disabled = true;
		var opt = {
			type : 'chat',
			fileInputId : fileInputId,
			to : to,
			onFileUploadError : function(error) {
				$('#fileModal').modal('hide');
				var messageContent = error.msg + ",发送图片文件失败:" + filename;
				appendMsg(curUserId, to, messageContent);
			},
			onFileUploadComplete : function(data) {
				$('#fileModal').modal('hide');
				var file = document.getElementById(fileInputId);
				if (file && file.files) {
					var objUrl = getObjectURL(file.files[0]);
					if (objUrl) {
						var img = document.createElement("img");
						img.src = objUrl;
						img.width = maxWidth;
					}
				}
				appendMsg(curUserId, to, {
					data : [ {
						type : 'pic',
						filename : filename,
						data : img
					} ]
				});
				var urlStr = serverPath + "/server/register.do";
				var jsonStr = '{method:"insertChatRecord",from:"' + curUserId
						+ '",to:"' + to + '",msgtext:"' + img + '",type:"img"}';
				// UseAjax(urlStr, jsonStr, document.cookie, '1');
				$.ajax({
					type : 'POST',
					url : urlStr,
					data : {
						"jsonStr" : jsonStr
					},
					success : function(response) {
						alert(response);

					},
					dataType : "json"
				});
			}
		};

		if (curChatUserId.indexOf(groupFlagMark) >= 0) {
			opt.type = 'groupchat';
			opt.to = curRoomId;
		}
		opt.apiUrl = apiURL;
		conn.sendPicture(opt);
		return;
	}
	$('#send-file-warning').html(
			"<font color='#FF0000'>不支持此图片类型" + filetype + "</font>");
};
var audtype = {
	"mp3" : true,
	"wma" : true,
	"wav" : true,
	"amr" : true,
	"avi" : true
};
// 发送音频消息时调用的方法
var sendAudio = function() {
	var to = curChatUserId;
	if (to == null) {
		return;
	}
	// 利用easemobwebim-sdk提供的方法来构造一个file对象
	var fileObj = Easemob.im.Helper.getFileUrl(fileInputId);
	if (fileObj.url == null || fileObj.url == '') {
		$('#send-file-warning').html("<font color='#FF0000'>请选择发送音频</font>");
		return;
	}
	var filetype = fileObj.filetype;
	var filename = fileObj.filename;
	if (filetype in audtype) {
		document.getElementById("fileSend").disabled = true;
		document.getElementById("cancelfileSend").disabled = true;
		var opt = {
			type : "chat",
			fileInputId : fileInputId,
			to : to,// 发给谁
			onFileUploadError : function(error) {
				$('#fileModal').modal('hide');
				var messageContent = error.msg + ",发送音频失败:" + filename;
				appendMsg(curUserId, to, messageContent);
			},
			onFileUploadComplete : function(data) {
				var messageContent = "发送音频" + filename;
				$('#fileModal').modal('hide');
				appendMsg(curUserId, to, messageContent);
			}
		};
		// 构造完opt对象后调用easemobwebim-sdk中发送音频的方法
		if (curChatUserId.indexOf(groupFlagMark) >= 0) {
			opt.type = 'groupchat';
			opt.to = curRoomId;
		}
		opt.apiUrl = apiURL;
		conn.sendAudio(opt);
		return;
	}
	$('#send-file-warning').html(
			"<font color='#FF0000'>不支持此音频类型" + filetype + "</font>");
};
// easemobwebim-sdk收到文本消息的回调方法的实现
var handleTextMessage = function(message) {
	var from = message.from;// 消息的发送者
	var mestype = message.type;// 消息发送的类型是群组消息还是个人消息
	var messageContent = message.data;// 文本消息体
	// TODO 根据消息体的to值去定位那个群组的聊天记录
	var room = message.to;
	if (mestype == 'groupchat') {
		appendMsg(message.from, message.to, messageContent, mestype);
	} else {
		//alert("shoudao" + from);
		insertChatRecord1(messageContent, "text", from);// !!!
		appendMsg(from, from, messageContent);

	}
};
// easemobwebim-sdk收到表情消息的回调方法的实现，message为表情符号和文本的消息对象，文本和表情符号sdk中做了
// 统一的处理，不需要用户自己区别字符是文本还是表情符号。
var handleEmotion = function(message) {
	var from = message.from;
	var room = message.to;
	var mestype = message.type;// 消息发送的类型是群组消息还是个人消息
	if (mestype == 'groupchat') {
		appendMsg(message.from, message.to, message, mestype);
	} else {
		appendMsg(from, from, message);
	}

};
// easemobwebim-sdk收到图片消息的回调方法的实现
var handlePictureMessage = function(message) {
	var filename = message.filename;// 文件名称，带文件扩展名
	var from = message.from;// 文件的发送者
	var mestype = message.type;// 消息发送的类型是群组消息还是个人消息
	var contactDivId = from;
	if (mestype == 'groupchat') {
		contactDivId = groupFlagMark + message.to;
	}
	var options = message;
	// 图片消息下载成功后的处理逻辑
	options.onFileDownloadComplete = function(response, xhr) {
		var objectURL = window.URL.createObjectURL(response);
		img = document.createElement("img");
		img.onload = function(e) {
			img.onload = null;
			window.URL.revokeObjectURL(img.src);
		};
		img.onerror = function() {
			img.onerror = null;
			if (typeof FileReader == 'undefined') {
				img.alter = "当前浏览器不支持blob方式";
				return;
			}
			img.onerror = function() {
				img.alter = "当前浏览器不支持blob方式";
			};
			var reader = new FileReader();
			reader.onload = function(event) {
				img.src = this.result;
			};
			reader.readAsDataURL(response);
		}
		img.src = objectURL;
		var pic_real_width = options.width;

		if (pic_real_width == 0) {
			$("<img/>").attr("src", objectURL).load(function() {
				pic_real_width = this.width;
				if (pic_real_width > maxWidth) {
					img.width = maxWidth;
				} else {
					img.width = pic_real_width;
				}
				appendMsg(from, contactDivId, {
					data : [ {
						type : 'pic',
						filename : filename,
						data : img
					} ]
				});

			});
		} else {
			if (pic_real_width > maxWidth) {
				img.width = maxWidth;
			} else {
				img.width = pic_real_width;
			}
			appendMsg(from, contactDivId, {
				data : [ {
					type : 'pic',
					filename : filename,
					data : img
				} ]
			});
		}
	};

	var redownLoadFileNum = 0;
	options.onFileDownloadError = function(e) {
		// 下载失败时只重新下载一次
		if (redownLoadFileNum < 1) {
			redownLoadFileNum++;
			options.accessToken = options_c;
			Easemob.im.Helper.download(options);

		} else {
			appendMsg(from, contactDivId, e.msg + ",下载图片" + filename + "失败");
			redownLoadFileNum = 0;
		}

	};
	// easemobwebim-sdk包装的下载文件对象的统一处理方法。
	Easemob.im.Helper.download(options);
};

// easemobwebim-sdk收到音频消息回调方法的实现
var handleAudioMessage = function(message) {
	var filename = message.filename;
	var filetype = message.filetype;
	var from = message.from;

	var mestype = message.type;// 消息发送的类型是群组消息还是个人消息
	var contactDivId = from;
	if (mestype == 'groupchat') {
		contactDivId = groupFlagMark + message.to;
	}
	var options = message;
	options.onFileDownloadComplete = function(response, xhr) {
		var objectURL = window.URL.createObjectURL(response);
		var audio = document.createElement("audio");
		if (("src" in audio) && ("controls" in audio)) {
			audio.onload = function() {
				audio.onload = null;
				window.URL.revokeObjectURL(audio.src);
			};
			audio.onerror = function() {
				audio.onerror = null;
				appendMsg(from, contactDivId, "当前浏览器不支持播放此音频:" + filename);
			};
			audio.controls = "controls";
			audio.src = objectURL;
			appendMsg(from, contactDivId, {
				data : [ {
					type : 'audio',
					filename : filename,
					data : audio
				} ]
			});
			// audio.play();
			return;
		}
	};
	options.onFileDownloadError = function(e) {
		appendMsg(from, contactDivId, e.msg + ",下载音频" + filename + "失败");
	};
	options.headers = {
		"Accept" : "audio/mp3"
	};
	Easemob.im.Helper.download(options);
};

// 处理收到文件消息
var handleFileMessage = function(message) {
	var filename = message.filename;
	var filetype = message.filetype;
	var from = message.from;

	var mestype = message.type;// 消息发送的类型是群组消息还是个人消息
	var contactDivId = from;
	if (mestype == 'groupchat') {
		contactDivId = groupFlagMark + message.to;
	}
	var options = message;
	options.onFileDownloadComplete = function(response, xhr) {
		var spans = "收到文件消息:" + filename + '   ';
		var content = spans + "【<a href='"
				+ window.URL.createObjectURL(response) + "' download='"
				+ filename + "'>另存为</a>】";
		appendMsg(from, contactDivId, content);
		return;
	};
	options.onFileDownloadError = function(e) {
		appendMsg(from, contactDivId, e.msg + ",下载文件" + filename + "失败");
	};
	Easemob.im.Helper.download(options);
};

// 收到视频消息
var handleVideoMessage = function(message) {

	var filename = message.filename;
	var filetype = message.filetype;
	var from = message.from;

	var mestype = message.type;// 消息发送的类型是群组消息还是个人消息
	var contactDivId = from;
	if (mestype == 'groupchat') {
		contactDivId = groupFlagMark + message.to;
	}
	var options = message;
	options.onFileDownloadComplete = function(response, xhr) {
		// var spans = "收到视频消息:" + filename;
		// appendMsg(from, contactDivId, spans);
		var objectURL = window.URL.createObjectURL(response);
		var video = document.createElement("video");
		if (("src" in video) && ("controls" in video)) {
			video.onload = function() {
				video.onload = null;
				window.URL.revokeObjectURL(video.src);
			};
			video.onerror = function() {
				video.onerror = null;
				appendMsg(from, contactDivId, "当前浏览器不支持播放此音频:" + filename);
			};
			video.src = objectURL;
			video.controls = "controls";
			video.width = "320";
			video.height = "240";
			appendMsg(from, contactDivId, {
				data : [ {
					type : 'video',
					filename : filename,
					data : video
				} ]
			});
			// audio.play();
			return;
		}

	};
	options.onFileDownloadError = function(e) {
		appendMsg(from, contactDivId, e.msg + ",下载音频" + filename + "失败");
	};
	Easemob.im.Helper.download(options);
};

var handleLocationMessage = function(message) {
	var from = message.from;
	var to = message.to;
	var mestype = message.type;
	var content = message.addr;
	if (mestype == 'groupchat') {
		appendMsg(from, to, content, mestype);
	} else {
		appendMsg(from, from, content, mestype);
	}
};
// 收到陌生人消息时创建陌生人列表
var createMomogrouplistUL = function createMomogrouplistUL(who, message) {
	var momogrouplistUL = document.getElementById("momogrouplistUL");
	var cache = {};

	if (who in cache) {
		return;
	}
	cache[who] = true;
	var lielem = document.createElement("li");
	$(lielem).attr({
		'id' : who,
		'class' : 'offline',
		'className' : 'offline',
		'type' : 'chat',
		'displayName' : who
	});
	lielem.onclick = function() {
		//alert("点你妹啊！");
		chooseContactDivClick(this);
	};
	var imgelem = document.createElement("img");
	imgelem.setAttribute("src", "img/head/contact_normal.png");
	lielem.appendChild(imgelem);

	var spanelem = document.createElement("span");
	spanelem.innerHTML = who;
	lielem.appendChild(spanelem);

	momogrouplistUL.appendChild(lielem);
};
// 显示聊天记录的统一处理方法
var appendMsg = function(who, contact, message, chattype) {
	// var contactUL = document.getElementById("contactlistUL");
	//alert("消息" + contact);
	var contactDivId = contact;
	// if (chattype && chattype == 'groupchat') {
	// contactDivId = groupFlagMark + contact;
	// }
	var contactLi = document.getElementById(contactDivId);
	//alert("contactLi" + contactLi);
	if (contactLi == null) {
		createMomogrouplistUL(who, message);
	}
	// createMomogrouplistUL(who, message);
	// 消息体 {isemotion:true;body:[{type:txt,msg:ssss}{type:emotion,msg:imgdata}]}
	var localMsg = null;
	if (typeof message == 'string') {
		localMsg = Easemob.im.Helper.parseTextMessage(message);
		localMsg = localMsg.body;
	} else {
		localMsg = message.data;
	}
	var headstr = [ "<p1>" + who + "   <span></span>" + "   </p1>",
			"<p2>" + getLoacalTimeString() + "<b></b><br/></p2>" ];
	var header = $(headstr.join(''));

	var lineDiv = document.createElement("div");
	for (var i = 0; i < header.length; i++) {
		var ele = header[i];
		lineDiv.appendChild(ele);
	}
	var messageContent = localMsg;
	for (var i = 0; i < messageContent.length; i++) {
		var msg = messageContent[i];
		var type = msg.type;
		var data = msg.data;
		if (type == "emotion") {
			var eletext = "<p3><img src='" + data + "'/></p3>";
			var ele = $(eletext);
			for (var j = 0; j < ele.length; j++) {
				lineDiv.appendChild(ele[j]);
			}
		} else if (type == "pic" || type == 'audio' || type == 'video') {
			var filename = msg.filename;
			var fileele = $("<p3>" + filename + "</p3><br>");
			for (var j = 0; j < fileele.length; j++) {
				lineDiv.appendChild(fileele[j]);
			}
			lineDiv.appendChild(data);
		} else {
			var eletext = "<p3>" + data + "</p3>";
			var ele = $(eletext);
			ele[0].setAttribute("class", "chat-content-p3");
			ele[0].setAttribute("className", "chat-content-p3");
			if (curUserId == who) {
				ele[0].style.backgroundColor = "#EBEBEB";
			}
			for (var j = 0; j < ele.length; j++) {
				lineDiv.appendChild(ele[j]);
			}
		}
	}
	if (curChatUserId == null && chattype == null) {
		setCurrentContact(contact);
		if (time < 1) {
			$('#accordion3').click();
			time++;
		}
	}
	if (curChatUserId && curChatUserId.indexOf(contact) < 0) {
		var contactLi = document.getElementById(contactDivId);
		if (contactLi == null) {
			return;
		}
		contactLi.style.backgroundColor = "green";
		var badgespan = $(contactLi).children(".badge");
		if (badgespan && badgespan.length > 0) {
			var count = badgespan.text();
			var myNum = new Number(count);
			myNum++;
			badgespan.text(myNum);

		} else {
			$(contactLi).append('<span class="badge">1</span>');
		}
		// 联系人不同分组的未读消息提醒
		var badgespanGroup = $(contactLi).parent().parent().parent().prev()
				.children().children(".badgegroup");
		if (badgespanGroup && badgespanGroup.length == 0) {
			$(contactLi).parent().parent().parent().prev().children().append(
					'<span class="badgegroup">New</span>');
		}

	}
	var msgContentDiv = getContactChatDiv(contactDivId);
	if (curUserId == who) {
		lineDiv.style.textAlign = "right";
	} else {
		lineDiv.style.textAlign = "left";
	}
	var create = false;
	if (msgContentDiv == null) {
		msgContentDiv = createContactChatDiv(contactDivId);
		create = true;
	}
	msgContentDiv.appendChild(lineDiv);
	if (create) {
		document.getElementById(msgCardDivId).appendChild(msgContentDiv);
	}
	msgContentDiv.scrollTop = msgContentDiv.scrollHeight;
	return lineDiv;

};
// 添加输入框鼠标焦点进入时清空输入框中的内容
var clearInputValue = function(inputId) {
	$('#' + inputId).val('');
};

// 清除聊天记录
var clearCurrentChat = function clearCurrentChat() {
	var currentDiv = getContactChatDiv(curChatUserId)
			|| createContactChatDiv(curChatUserId);
	currentDiv.innerHTML = "";
};

var showRegist = function showRegist() {
	$('#loginmodal').modal('hide');
	$('#regist-div-modal').modal('toggle');
};

var getObjectURL = function getObjectURL(file) {
	var url = null;
	if (window.createObjectURL != undefined) { // basic
		url = window.createObjectURL(file);
	} else if (window.URL != undefined) { // mozilla(firefox)
		url = window.URL.createObjectURL(file);
	} else if (window.webkitURL != undefined) { // webkit or chrome
		url = window.webkitURL.createObjectURL(file);
	}
	return url;
};
var getLoacalTimeString = function getLoacalTimeString() {
	var date = new Date();
	var time = date.getHours() + ":" + date.getMinutes() + ":"
			+ date.getSeconds();
	return time;
};
// 选择联系人的处理

// var getContactLi = function(chatUserId) {
// alert("得到"+document.getElementById(chatUserId));
//	  
// return
// };

// 显示当前选中联系人的聊天窗口div，并将该联系人在联系人列表中背景色置为蓝色
var showContactChatDiv = function(chatUserId) {
	var contentDiv = getContactChatDiv(chatUserId);
	if (contentDiv == null) {
		//alert("没有聊天串");
		contentDiv = createContactChatDiv(chatUserId);
		document.getElementById(msgCardDivId).appendChild(contentDiv);
	}
	contentDiv.style.display = "block";
	var contactLi = document.getElementById(chatUserId);
	if (contactLi == null) {
		return;
	}
	contactLi.style.backgroundColor = "#33CCFF";
	var dispalyTitle = null;// 聊天窗口显示当前对话人名称
	// if (chatUserId.indexOf(groupFlagMark) >= 0) {
	// dispalyTitle = "群组" + $(contactLi).attr('displayname') + "聊天中";
	// curRoomId = $(contactLi).attr('roomid');
	// $("#roomMemberImg").css('display', 'block');
	// } else {
	// alert("yu" + chatUserId);
	dispalyTitle = "与" + chatUserId + "聊天中";
	$("#roomMemberImg").css('display', 'none');
	// }

	document.getElementById(talkToDivId).children[0].innerHTML = dispalyTitle;
};
// 构造联系人列表
var buildContactDiv = function(contactlistDivId, roster) {
	var uielem = document.getElementById("contactlistUL");
	var cache = {};
	for (i = 0; i < roster.length; i++) {
		if (!(roster[i].subscription == 'both' || roster[i].subscription == 'from')) {
			continue;
		}
		var jid = roster[i].jid;
		var userName = jid.substring(jid.indexOf("_") + 1).split("@")[0];
		if (userName in cache) {
			continue;
		}
		cache[userName] = true;
		var lielem = $('<li>').attr({
			'id' : userName,
			'class' : 'offline',
			'className' : 'offline',
			'type' : 'chat',
			'displayName' : userName
		}).click(function() {
			chooseContactDivClick(this);
		});
		$('<img>').attr("src", "img/head/contact_normal.png").appendTo(lielem);
		$('<span>').html(userName).appendTo(lielem);
		$('#contactlistUL').append(lielem);
	}
	var contactlist = document.getElementById(contactlistDivId);
	var children = contactlist.children;
	if (children.length > 0) {
		contactlist.removeChild(children[0]);
	}
	contactlist.appendChild(uielem);
};

// 切换联系人聊天窗口div
var chooseContactDivClick = function(li) {
	var chatUserId = li.id;
	if ($(li).attr("type") == 'groupchat' && ('true' != $(li).attr("joined"))) {
		conn.join({
			roomId : $(li).attr("roomId")
		});
		$(li).attr("joined", "true");
	}
	if (chatUserId != curChatUserId) {
		if (curChatUserId == null) {
			showContactChatDiv(chatUserId);
		} else {
			showContactChatDiv(chatUserId);
			hiddenContactChatDiv(curChatUserId);
		}
		curChatUserId = chatUserId;
	}
	// 对默认的null-nouser div进行处理,走的这里说明联系人列表肯定不为空所以对默认的聊天div进行处理
	$('#null-nouser').css({
		"display" : "none"
	});
	var badgespan = $(li).children(".badge");
	if (badgespan && badgespan.length > 0) {
		li.removeChild(li.children[2]);
	}

	// 点击有未读消息对象时对未读消息提醒的处理
	var badgespanGroup = $(li).parent().parent().parent().find(".badge");
	if (badgespanGroup && badgespanGroup.length == 0) {
		$(li).parent().parent().parent().prev().children().children().remove();
	}
};

// 对上一个联系人的聊天窗口div做隐藏处理，并将联系人列表中选择的联系人背景色置空
var hiddenContactChatDiv = function(chatUserId) {
	var contactLi = document.getElementById(chatUserId);
	if (contactLi) {
		contactLi.style.backgroundColor = "";
	}
	var contentDiv = getContactChatDiv(chatUserId);
	if (contentDiv) {
		contentDiv.style.display = "none";

	}

};
// easemobwebim-sdk中处理出席状态操作
var handleRoster = function(rosterMsg) {
	for (var i = 0; i < rosterMsg.length; i++) {
		var contact = rosterMsg[i];
		if (contact.ask && contact.ask == 'subscribe') {
			continue;
		}
		if (contact.subscription == 'to') {
			toRoster.push({
				name : contact.name,
				jid : contact.jid,
				subscription : "to"
			});
		}
		// app端删除好友后web端要同时判断状态from做删除对方的操作
		if (contact.subscription == 'from') {
			toRoster.push({
				name : contact.name,
				jid : contact.jid,
				subscription : "from"
			});
		}
		if (contact.subscription == 'both') {
			var isexist = contains(bothRoster, contact);
			if (!isexist) {
				var lielem = $('<li>').attr({
					"id" : contact.name,
					"class" : "offline",
					"className" : "offline"
				}).click(function() {
					chooseContactDivClick(this);
				});
				$('<img>').attr({
					"src" : "img/head/contact_normal.png"
				}).appendTo(lielem);

				$('<span>').html(contact.name).appendTo(lielem);
				$('#contactlistUL').append(lielem);
				bothRoster.push(contact);
			}
		}
		if (contact.subscription == 'remove') {
			var isexist = contains(bothRoster, contact);
			if (isexist) {
				removeFriendDomElement(contact.name);
			}
		}
	}
};

// 判断要操作的联系人和当前联系人列表的关系
var contains = function(roster, contact) {
	var i = roster.length;
	while (i--) {
		if (roster[i].name === contact.name) {
			return true;
		}
	}
	return false;
};